package com.meshnetics.gb.type.impl.additional;

import com.meshnetics.gb.type.DataType;
import com.meshnetics.gb.type.DataValue;

import java.nio.ByteBuffer;

/**
 * Simple wrapper for toString operation - add prefix before
 * toString of wrapped object.
 *
 * @author Yury Aserchev (yaserchev@meshnetics.com)
 *         Date: 27.08.2008 21:17:59
 */
public final class ToStringWrapper implements DataValue {
    private final String prefix;
    private final DataValue object;

    public static ToStringWrapper create(final DataValue object, final String prefix) {
        if (object == null) {
            return null;
        } else {
            return new ToStringWrapper(object, prefix);
        }
    }

    private ToStringWrapper(final DataValue object, final String prefix) {
        if (prefix == null) {
            throw new NullPointerException("parameter prefix is null");
        }
        this.prefix = prefix;
        this.object = object;
    }

    public int getDataSize() {
        return object.getDataSize();
    }

    public byte[] bytesValue() {
        return object.bytesValue();
    }

    public Object toObject() {
        return object.toObject();
    }

    public void serialize(final ByteBuffer buffer) {
        object.serialize(buffer);
    }

    public DataType getType() {
        return object.getType();
    }

    public String stringValue() {
        return object.stringValue();
    }

    public String toString() {
        if (object instanceof Enumeration) {
            return prefix + ((Enumeration) object).getSimpleString();
        } else {
            return prefix + object.toString();
        }
    }

    public int hashCode() {
        return object.hashCode();
    }

    public boolean equals(final Object obj) {
        if (obj instanceof ToStringWrapper) {
            final ToStringWrapper that = (ToStringWrapper) obj;
            return obj.equals(that.object);
        } else {
            return object.equals(obj);
        }
    }
}